package com.bening.smsapp.factory;

import com.bening.smsapp.bootstrap.BootConfigParameters;
import com.bening.smsapp.constant.SmsAppConstant;
import oracle.jdbc.*;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import com.bening.smsapp.dao.*;
import java.sql.*;


public class SmsAppFactory
{
    static SmsAppFactory theInstance = null;
    static BasicDataSource dataSource = null;
    static BootConfigParameters params = BootConfigParameters.getInstance();
    
    static
    {
        final Logger logger = Logger.getLogger( SmsAppFactory.class );

        theInstance = new SmsAppFactory();
        dataSource = new BasicDataSource();

        try
        {
            Class.forName( params.getDbJdbcClass() );
        }
        catch ( ClassNotFoundException e )
        {
            logger.fatal( "[db] error, JDBC class '" + params.getDbJdbcClass() + "' not found." );
            
        }

        System.out.println("[db] setting parameter for db pool");
        dataSource.setDriverClassName( params.getDbJdbcClass() );
        dataSource.setUsername( params.getDbUser() );
        dataSource.setPassword( params.getDbPass() );
        dataSource.setUrl( params.getDbUri() );
        
        dataSource.setMaxActive(params.getMaxActive());
        dataSource.setMaxOpenPreparedStatements(params.getMaxOpenPreparedStatements());
        dataSource.setMaxWait(params.getMaxWait());
        dataSource.setMaxIdle(params.getMaxIdle());
        
    }

    /**
     * this method returns a database connection objects.
     * this method produce a database connection
     * @return database conection
     */
    public static Connection getDbConnection()
    {
        final Logger logger = Logger.getLogger( SmsAppFactory.class );
        final String METHOD_SIGNATURE = "[db]";

        Connection conn = null;

        try
        {
            //conn = dataSource.getConnection();
        	conn = DriverManager.getConnection (params.getDbUri(),params.getDbUser(),params.getDbPass());
        	
        }
        catch ( SQLException e )
        {
            logger.error( METHOD_SIGNATURE + "SqlException", e );
            
        }

        return conn;
    }
    
    public static SmsAppDao getDaoObject() {
    	if(params.getDaoImpl().equals(SmsAppConstant.PREPSTMT_IMPL))
    		return new SmsAppDaoImpl();
    	else if(params.getDaoImpl().equals(SmsAppConstant.SQLLDR_IMPL))
    		return new SmsAppSQLLDRImpl();
    	else
    		return new SmsAppDaoImpl();
    }
}
